
#import "UIView+X.h"
#import "UIColor+X.h"
#import <QuartzCore/QuartzCore.h>


@implementation UIView (X)


/**
 * 为视图添加灰色的圆角边界
 * @result
 */
- (void)addCornerBorder {
    [self addCornerBorderWithColor:[UIColor colorWithHex:0xd1d1d1]];
}


- (void)addCornerBorderWithColor:(UIColor*)color {
    [self addCornerBorderWithColor:color width:1 radius:5 maskToBounds:YES];
}


- (void)addCornerBorderWithColor:(UIColor *)color
                           width:(int)width
                          radius:(int)radius
                    maskToBounds:(BOOL)flag {
    self.layer.masksToBounds = flag;
    self.layer.borderWidth = width;
    self.layer.cornerRadius = radius;
    self.layer.borderColor = [color CGColor];
}


/**
 * 根据制定的背景色、边框颜色、边框宽度和圆角半径，将对应效果的view转换成image
 * @param   bgColor 背景色，若nil，则不设置背景色
 * @param   borderColor 边框色，若nil，则不设置边框色
 * @param   width 边框宽度， 若为0，则不设置边框宽度
 * @param   radius 圆角半径，若为0，则不设置圆角
 * @result
 */
- (UIImage*)imageForBgColor:(UIColor*)bgColor
                borderColor:(UIColor*)borderColor
                borderWidth:(int)width
               cornerRadius:(int)radius {
    UIImage *image = nil;
    
    @autoreleasepool {
        CGRect rect = CGRectZero;
        rect.size = self.frame.size;
        UIView *tmpView = [[UIView alloc] initWithFrame:rect];
        
        // 在副本上设置边框和背景
        if (bgColor) {
            tmpView.backgroundColor = bgColor;
        }
        if (borderColor) {
            tmpView.layer.borderColor = borderColor.CGColor;
        }
        if (width > 0) {
            tmpView.layer.borderWidth = width;
        }
        
        if (radius > 0 ) {
            tmpView.layer.cornerRadius = radius;
        }
        
        // 将副本转成image
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        [tmpView.layer renderInContext:ctx];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    return image;
}

@end

